package entity

import (
	"github.com/jinzhu/gorm"
)

type Category struct {
	ID            uint   `json:"id"`
	CategoryName  string `json:"category_name"`
	CategoryDes   string `json:"category_des"`
	CoverImageUrl string `json:"cover_image_url"`
}

func (c *Category) Get(db *gorm.DB) ([]Category, error) {
	var classList []Category
	err := db.Find(&classList).Error
	if err != nil {
		return nil, err
	}
	return classList, nil
}

func (c *Category) Create(db *gorm.DB) error {
	return db.Create(&c).Error
}

func (c *Category) GetCategoryNameByID(db *gorm.DB) (string, error) {
	err := db.First(&c).Where("id = ?", c.ID).Error
	if err != nil {
		return "", err
	}
	return c.CategoryName, nil
}

func (c *Category) GetByPagination(db *gorm.DB, offset, pageSize int) ([]Category, error) {
	var list []Category
	err := db.Offset(offset).Limit(pageSize).Find(&list).Error
	if gorm.ErrRecordNotFound == err {
		return list, nil
	} else {
		return list, err
	}
}

func (c *Category) Count(db *gorm.DB) (int, error) {
	cnt := 0
	err := db.Model(c).Count(&cnt).Error
	return cnt, err
}

func (c *Category) Update(db *gorm.DB) error {
	return db.Save(c).Error
}

func (c *Category) Delete(db *gorm.DB) error {
	return db.Delete(&c).Error
}

func (c *Category) GetBySearchText(db *gorm.DB, text string) ([]Category, error) {
	var list []Category
	err := db.Where("category_name like ?", "%"+text+"%").Find(&list).Error
	return list, err
}
